﻿import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import FilUI

import "../controls"
import "../page"
import SecAssistPro

Rectangle {
    id: control
    width: 300
    height: 200
    color: "transparent"

    property StackView parentStackView
    property string modifyPid: ""
    property alias selectItemText: id_filtext__selectItemText.text

    // public controls
    property alias filIconButton__switchDownloadMode: id_filIconButton__switchDownloadMode
    property alias filIconButton__add: id_filIconButton__add
    property alias filIconButton__remove: id_filIconButton__remove
    property alias rectangle__currentSelection: id_rectangle__currentSelection
    property alias filIconButton__override: id_filIconButton__override
    property alias filTableView: id_filtableview

    signal addClick()
    signal modifyClick(var pid)
    signal deleteClick()

    onAddClick: {
        parentStackView.push(id_component__newprojectpage)
    }
    onModifyClick: (pid) => {
        console.log("onModifyClick pid: ", pid)
        control.modifyPid = pid
        parentStackView.push(id_component__modifyprojectpage)
    }

    QtObject {
        id: d
        property alias id_filmenu__switchDownloadMode: id_filmenu__switchDownloadMode
    }

    Component {
        id: id_component__newprojectpage
        NewProjectPage {
            id: id_newprojectpage
            parentStackView: control.parentStackView
        }
    }

    Component {
        id: id_component__modifyprojectpage
        ModifyProjectPage {
            id: id_modifyprojectpage
            parentStackView: control.parentStackView
            modifyPid: control.modifyPid
        }
    }

    ColumnLayout {
        anchors.fill: parent
        Rectangle {
            color: control.color
            Layout.preferredHeight: 35
            Layout.preferredWidth: parent.width
            anchors.margins: 3
            RowLayout {
                spacing: 3
                anchors.fill: parent
                FilIconButton {
                    id: id_filIconButton__switchDownloadMode
                    text: qsTr("Switch Download Mode")
                    Layout.preferredWidth: 30
                    Layout.preferredHeight: 30
                    Layout.alignment: Qt.AlignVCenter
                    iconSource: FilIcons.ChromeSwitch
                    iconSize: 15
                    onClicked: {
                        id_filmenu__switchDownloadMode.popup()
                    }
                    FilMenu {
                        id: id_filmenu__switchDownloadMode
                        title: qsTr("Switch Download Mode")
                        Component.onCompleted: {
                            var index = SettingsHelper.getAppDownloadMode(0)
                            selectSingle(index)
                        }
                        FilMenuItem {
                            id: id_filmenuitem__default
                            text: qsTr("Default Mode")
                            checkable: true
                            onTriggered: {
                                id_filmenu__switchDownloadMode.selectSingle(0)
                                SettingsHelper.saveAppDownloadMode(0)
                            }
                        }
                        FilMenuItem {
                            id: id_filmenuitem__project
                            text: qsTr("Project Mode")
                            checkable: true
                            onTriggered: {
                                id_filmenu__switchDownloadMode.selectSingle(1)
                                SettingsHelper.saveAppDownloadMode(1)
                            }
                        }
                        function selectSingle(index) {
                            // reset all checked selection
                            id_filmenuitem__default.checked = false
                            id_filmenuitem__project.checked = false
                            // set single checked
                            console.log("selectSingle index =", index)
                            switch(index) {
                            case 0:
                                id_filmenuitem__default.checked = true
                                control.selectItemText = SettingsHelper.getAppDownloadDir()
                                break
                            case 1:
                                id_filmenuitem__project.checked = true
                                var pname = id_item__tableview.getCurrentSelectProjectName()
                                if (pname.length > 0) {
                                    control.selectItemText = pname
                                } else {
                                    control.selectItemText = qsTr("null")
                                }
                                break
                            default:
                                console.warn("out of range")
                            }
                        }
                    }
                }
                FilIconButton {
                    id: id_filIconButton__add
                    text: qsTr("Add Project")
                    Layout.preferredWidth: 30
                    Layout.preferredHeight: 30
                    Layout.alignment: Qt.AlignVCenter
                    iconSource: FilIcons.Add
                    iconSize: 15
                    onClicked: {
                        addClick()
                    }
                }
                FilIconButton {
                    id: id_filIconButton__remove
                    text: qsTr("Remove Project")
                    Layout.preferredWidth: 30
                    Layout.preferredHeight: 30
                    Layout.alignment: Qt.AlignVCenter
                    iconSource: FilIcons.Remove
                    iconSize: 15
                    onClicked: {
                        if (id_item__tableview.getCurrentSelectProjectPid().length > 0) {
                            console.log("Confirm deletion in a pop-up box: %1".arg(id_item__tableview.getCurrentSelectProjectPid()))
                            id_filcontentdialog__delete.open()
                        }
                    }
                    FilContentDialog {
                        id: id_filcontentdialog__delete
                        implicitWidth: 500
                        title: qsTr("Delete")
                        message: qsTr("Are you sure you want to delete this project? (PID: %1)").arg(id_item__tableview.getCurrentSelectProjectPid())
                        buttonFlags: FilContentDialogType.NegativeButton | FilContentDialogType.PositiveButton
                        onPositiveClicked: {
                            var pid = id_item__tableview.getCurrentSelectProjectPid()
                            if (ProjectFileWatcher.existsByPid(pid)) {
                                if (!ProjectFileWatcher.removeByPid(pid)) {
                                    console.log("ProjectFileWatcher removeByPid Failure.")
                                }
                            }
                            if(ProjectDbHelper.del()) {
                                id_item__tableview.loadDatabaseData()
                            } else {
                                showError(qsTr("Delete %1 Failure").arg(pid), 2)
                            }
                        }
                        onNegativeClicked: {
                            console.log("Cancel")
                        }
                    }
                }
                Item {
                    Layout.fillWidth: true
                    Layout.preferredHeight: parent.height
                    Layout.alignment: Qt.AlignVCenter
                    Rectangle {
                        id: id_rectangle__currentSelection
                        anchors.fill: parent
                        color: Window.active ? FilTheme.frameActiveColor : FilTheme.frameColor
                        radius: 5
                        RowLayout {
                            anchors.centerIn: parent
                            FilText {
                                text: qsTr("Current Selection : ")
                            }
                            FilText {
                                id: id_filtext__selectItemText
                                font: FilTextStyle.BodyStrong
                            }
                        }
                    }
                }
                FilRadioButton {
                    id: id_filIconButton__override
                    Layout.preferredWidth: 90
                    text: qsTr("Override")
                    onCheckedChanged: {
                        SettingsHelper.saveAppDownloadOverride(checked)
                    }
                    Component.onCompleted: {
                        checked = SettingsHelper.getAppDownloadOverride()
                    }
                    FilToolTip {
                        text: qsTr("Overwrite the file with the same name when the download is complete")
                        delay: 1000
                        visible: parent.hovered
                    }
                }

/*
                Item {
                    id: id_rect__search
                    property bool searching: false
                    property real itemWidth: 45
                    Layout.preferredWidth: itemWidth
                    Layout.preferredHeight: parent.height
                    Rectangle {
                        anchors.fill: parent
                        radius: 20
                        RowLayout {
                            anchors.fill: parent
                            anchors.leftMargin: 5
                            anchors.rightMargin: 3
                            spacing: 0
                            FilIconButton {
                                verticalPadding                      : 0
                                horizontalPadding                    : 0
                                iconSize: 16
                                iconSource: FilIcons.Search
                                color: Qt.rgba(0, 0, 0, 0)
                                iconColor: {
                                    if (!enabled) {
                                        return Qt.rgba(161/255, 161/255, 161/255, 1)
                                    }
                                    if (pressed) {
                                        return Qt.rgba(0, 0, 0, 0.6)
                                    }
                                    return hovered ? Qt.rgba(0, 0, 0, 0.3) : Qt.rgba(0, 0, 0, 1)
                                }
                                // background: Rectangle {
                                //     anchors.fill: parent
                                //     anchors.margins: 0
                                //     color: "blue"
                                //     anchors.centerIn: parent
                                // }
                                onClicked: {
                                    if (id_rect__search.searching == false) {
                                        id_rect__search.searching = true
                                        id_rect__search.itemWidth = 250
                                        id_filtextbox.visible = true
                                        id_filtextbox.enabled = true
                                    } else {
                                        id_filtextbox.clear()
                                        id_filtextbox.visible = false
                                        id_filtextbox.enabled = false
                                        id_rect__search.searching = false
                                        id_rect__search.itemWidth = 45
                                    }
                                }
                            }
                            FilTextBox {
                                id: id_filtextbox
                                Layout.fillWidth: true
                                Layout.preferredHeight: parent.height - 8
                                placeholderText: qsTr("Search")
                                padding: 0
                                leftPadding: 0
                                rightPadding: 33
                                cleanButton.color: Qt.rgba(0, 0, 0, 0)
                                background: Rectangle {
                                    anchors.fill: parent
                                    radius: 20
                                    // color: "green"
                                }
                            }
                        }
                    }

                    Behavior on itemWidth {
                        NumberAnimation { duration: 200; easing.type: Easing.OutCubic }
                    }
                }
*/
            }
        }
        Item {
            id: id_item__tableview
            Layout.fillHeight: true
            Layout.preferredWidth: parent.width

            property string nameKeyword: ""
            property string currentPid: ""
            property var dataSource: []
            property var dataSourceSearch: []

            onNameKeywordChanged: {
                id_filtableview.filter(function(item){
                    if(item.name.includes(nameKeyword)){
                        return true
                    }
                    return false
                })
            }

            FilMenu{
                id:pop_filter
                width: 200
                height: 89

                contentItem: Item{

                    onVisibleChanged: {
                        if(visible){
                            name_filter_text.text = id_item__tableview.nameKeyword
                            name_filter_text.cursorPosition = name_filter_text.text.length
                            name_filter_text.forceActiveFocus()
                        }
                    }

                    FilTextBox{
                        id:name_filter_text
                        anchors{
                            left: parent.left
                            right: parent.right
                            top: parent.top
                            leftMargin: 10
                            rightMargin: 10
                            topMargin: 10
                        }
                        iconSource: FilIcons.Search
                    }

                    FilButton{
                        text: qsTr("Search")
                        anchors{
                            bottom: parent.bottom
                            right: parent.right
                            bottomMargin: 10
                            rightMargin: 10
                        }
                        onClicked: {
                            id_item__tableview.nameKeyword = name_filter_text.text
                            pop_filter.close()
                        }
                    }

                }

                function showPopup(){
                    id_filtableview.closeEditor()
                    pop_filter.popup()
                }

            }

            ProjectDbHelperCallable {
                id: id_pdhc__readAll
                onStart: {
                    id_item__tableview.dataSource = []
                }
                onFinish: {
                    id_filtableview.dataSource = id_item__tableview.dataSource
                }
                onError: (result) => {
                    console.warn("id_pdhc__readAll onError, ", result)
                }
                onReadAll: (ppid, nname, wwdir, ddspath, rrds, uuspath, rrus, ffsw, llstime) => {
                    var obj = {
                        pid         : ppid,
                        name        : nname,
                        wdir        : wwdir,
                        dspath      : ddspath,
                        rds         : id_filtableview.customItem(com_checkbox_rds, {checked: rrds}),
                        uspath      : uuspath,
                        rus         : id_filtableview.customItem(com_checkbox_rus, {checked: rrus}),
                        fsw         : ffsw,
                        lstime      : llstime,
                        options     : id_filtableview.customItem(com_action),
                        _key        : FilTools.uuid()
                    }
                    id_item__tableview.dataSource.push(obj)
                }
            }

            ProjectDbHelperCallable {
                id: id_pdhc__search
                onStart: {
                    id_item__tableview.dataSourceSearch = []
                }
                onFinish: {
                    id_filtableview.dataSource = id_item__tableview.dataSourceSearch
                }
                onError: (result) => {
                    console.warn("id_pdhc__search onError, ", result)
                }
                onSearch: (ppid, nname, wwdir, ddspath, rrds, uuspath, rrus, ffsw, llstime) => {
                    id_item__tableview.dataSourceSearch.push({
                        pid         : ppid,
                        name        : nname,
                        wdir        : wwdir,
                        dspath      : ddspath,
                        rds         : id_filtableview.customItem(com_checkbox_rds, {checked: rrds}),
                        uspath      : uuspath,
                        rus         : id_filtableview.customItem(com_checkbox_rus, {checked: rrus}),
                        fsw         : ffsw,
                        lstime      : llstime,
                        options     : id_filtableview.customItem(com_action),
                        _key        : FilTools.uuid()
                    })
                }
            }

            Component {
                id: com_column_filter_name
                Item {
                    FilText {
                        text: qsTr("Name")
                        anchors.centerIn: parent
                    }
                    FilIconButton {
                        width: 20
                        height: 20
                        iconSize: 12
                        verticalPadding: 0
                        horizontalPadding: 0
                        iconSource: FilIcons.Filter
                        iconColor: {
                            if (id_item__tableview.nameKeyword) {
                                return Qt.rgba(76/255, 160/255, 224/255, 1)
                            }
                            return Qt.rgba(0,0,0,1)
                        }
                        anchors {
                            right: parent.right
                            rightMargin: 3
                            verticalCenter: parent.verticalCenter
                        }
                        onClicked: {
                            pop_filter.showPopup()
                        }
                    }
                }
            }

            Component {
                id: com_checkbox_rds
                Item {
                    FilCheckBox {
                        anchors.centerIn: parent
                        checked: true === options.checked
                        animationEnabled: FilTheme.animationEnabled
                        clickListener: function() {
                            var obj = id_filtableview.getRow(row)
                            obj.rds = id_filtableview.customItem(com_checkbox_rds, {checked: !options.checked})
                            id_filtableview.setRow(row, obj)
                            var pid = obj.pid
                            ProjectDbHelper.updateRecordByPid(pid, ProjectDbHelperColumnIndexType.CIT_RDS, "%1".arg(options.checked ? 1 : 0))
                        }
                    }
                }
            }

            Component {
                id: com_checkbox_rus
                Item {
                    FilCheckBox {
                        anchors.centerIn: parent
                        checked: true === options.checked
                        animationEnabled: FilTheme.animationEnabled
                        clickListener: function() {
                            var obj = id_filtableview.getRow(row)
                            obj.rus = id_filtableview.customItem(com_checkbox_rus, {checked: !options.checked})
                            id_filtableview.setRow(row, obj)
                            var pid = obj.pid
                            ProjectDbHelper.updateRecordByPid(pid, ProjectDbHelperColumnIndexType.CIT_RUS, "%1".arg(options.checked ? 1 : 0))
                        }
                    }
                }
            }

            Component {
                id: com_action
                Item {
                    RowLayout {
                        anchors.centerIn: parent
                        FilIconButton {
                            iconSource: FilIcons.More
                            iconSize: 14
                            onClicked: {
                                var obj = id_filtableview.getRow(row)
                                modifyClick(obj.pid)
                            }
                        }
                    }
                }
            }

            FilTableView {
                anchors.fill: parent
                id: id_filtableview
                radius: 5
                onRowsChanged: {

                }
                startRowIndex: 1
                columnSource: [
                    {
                        title: id_filtableview.customItem(com_column_filter_name, {title: qsTr("Name")}),
                        dataIndex: 'name',
                        width: 270,
                        readOnly: true
                    },
                    {
                        title: qsTr("WorkDir"),
                        dataIndex: 'wdir',
                        width: 300,
                        readOnly: true
                    },
                    {
                        title: qsTr("RDS"),
                        dataIndex: 'rds',
                        width: 60,
                        frozen: true
                    },
                    {
                        title: qsTr("RUS"),
                        dataIndex: 'rus',
                        width: 60,
                        frozen: true
                    },
                    {
                        title: qsTr("Options"),
                        dataIndex: 'options',
                        width: 80,
                        frozen: true
                    }
                ]
                onCurrentRowChanged: {
                    d.id_filmenu__switchDownloadMode.selectSingle(1)
                    SettingsHelper.saveAppDownloadMode(1)
                }
            }

            function getCurrentSelectProjectName() {
                var rowModel = id_filtableview.current
                if (rowModel) {
                    return rowModel.name
                }
                return ""
            }

            function getCurrentSelectProjectPid() {
                var rowModel = id_filtableview.current
                if (rowModel) {
                    return rowModel.pid
                }
                return ""
            }

            function saveCurrentSelectProjectPid() {
                console.log("saveCurrentSelectProjectPid ", getCurrentSelectProjectPid())
                SettingsHelper.saveLastSelectPid(getCurrentSelectProjectPid())
            }

            function loadDatabaseData() {
                console.log("loadDatabaseData")
                ProjectDbHelper.readAll(id_pdhc__readAll)
            }

            function search(text, type = ProjectDbHelper.CIT_NAME) {
                ProjectDbHelper.search(type, text, id_pdhc__search)
            }
        }
    }

    function refreshDataFromDatabase() {
        console.log("refreshDataFromDatabase")
        id_item__tableview.loadDatabaseData()
    }

    function getCurrentSelectProjectPid() {
        return id_item__tableview.getCurrentSelectProjectPid()
    }
}
